package com.baigu.tools;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baigu.tools.bean.Kuaidi100Info;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.List;

/**
 * 根据快递单号到快递100获取快递信息
 * Created by lzg on 2017/11/24.
 */
public class Kuaidi100Tool {

    private static final Logger LOG = LoggerFactory.getLogger(Kuaidi100Tool.class);
    private static OkHttpClient client = new OkHttpClient();

    /*
    https://m.kuaidi100.com/autonumber/auto?num=462944892322
    https://m.kuaidi100.com/query?type=zhongtong&postid=462944892322
     */

//    public static void getKuaidiInfo(String expressNo) {
//        Document doc = null;
//        try {
//            doc = Jsoup.connect("https://m.kuaidi100.com/result.jsp?nu=" + expressNo).get();
//            LOG.info(doc.title());
//            Elements codeInput = doc.select("#queryInput");
//            LOG.info(codeInput.val());
//        } catch (IOException e) {
//            LOG.error(e.getMessage(), e);
//        }
//    }

    public static List<Kuaidi100Info> getKuaidiInfo(String expressNo) {
        try {
            String comCode = getComCode(expressNo);
            if(comCode == null) {
                return null;
            }
            return getExpressInfo(expressNo, comCode);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
        return null;
    }

    private static String getComCode(String expressNo) throws IOException {
        Request request = new Request.Builder()
                .url("https://m.kuaidi100.com/autonumber/auto?num=" + expressNo)
                .build();
        Response response = client.newCall(request).execute();
        JSONArray ja = JSONArray.parseArray(response.body().string());
        if(CollectionUtils.isEmpty(ja)) {
            return null;
        }
        JSONObject jo = ja.getJSONObject(0);
        String comCode = jo.getString("comCode");
        return comCode;
    }

    private static List<Kuaidi100Info> getExpressInfo(String expressNo, String comCode) throws IOException {
        Request request = new Request.Builder()
                .url("https://m.kuaidi100.com/query?type=" + comCode + "&postid=" + expressNo)
                .build();
        Response response = client.newCall(request).execute();
        JSONObject jo = JSONObject.parseObject(response.body().string());
        JSONArray ja = jo.getJSONArray("data");
        return ja.toJavaList(Kuaidi100Info.class);
    }

    public static void main(String[] args) {
        List<Kuaidi100Info> infos = getKuaidiInfo("560654185330");
        LOG.info(JSON.toJSONString(infos));
    }
}
